﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Linq;
using Microsoft.SharePoint.WebPartPages;
using WebPart = System.Web.UI.WebControls.WebParts.WebPart;

namespace SharePointAccelerators.LinkButtons.LinksWebPart
{
    public enum DisplayTypeEnum
    { 
        Resizable,
        FixedSize,
        WebPartSize
    }

    public enum ButtonLayoutEnum
    {
        Horizonatal,
        Vertical
    }

    [ToolboxItemAttribute(false)]
    public class LinksWebPart : WebPart
    {
        private string _linksListName;

        [WebBrowsable(true),
        WebDescription("Select a links list you want to display."),
        WebDisplayName("Links list:"), 
        Personalizable(PersonalizationScope.Shared)]
        public string LinksListName
        {
            get
            {
                if (string.IsNullOrEmpty(_linksListName))
                {
                    return "Cool Links";
                }
                else
                {
                    return _linksListName;
                }
            }
            set
            {
                _linksListName = value;
            }
        }

        private string _listView;

        [WebBrowsable(true),
        WebDescription("Select a links list you want to display."),
        WebDisplayName("List View:"),
        Personalizable(PersonalizationScope.Shared)]
        public string ListView
        {
            get
            {
                if (string.IsNullOrEmpty(_listView))
                {
                    return "[Default]";
                }
                else
                {
                    return _listView;
                }
            }

            set
            {
                _listView = value;
            }
        }

        private DisplayTypeEnum _displayType;

        [WebBrowsable(true),
        WebDescription("Select a links list you want to display."),
        WebDisplayName("Display Type:"),
        DefaultValue(DisplayTypeEnum.Resizable),
        Personalizable(PersonalizationScope.Shared)]
        public DisplayTypeEnum DisplayType
        {
            get
            {
                return _displayType;
            }

            set
            {
                _displayType = value;
            }
        }

        private ButtonLayoutEnum _buttonLayout;

        [WebBrowsable(true),
        WebDescription("Select a links list you want to display."),
        WebDisplayName("Button Layout:"),
        DefaultValue(ButtonLayoutEnum.Vertical),
        Personalizable(PersonalizationScope.Shared)]
        public ButtonLayoutEnum ButtonLayout
        {
            get
            {
                return _buttonLayout;
            }

            set
            {
                _buttonLayout = value;
            }
        }

        private int _width;

        [WebBrowsable(true),
        WebDescription("Select a links list you want to display."),
        WebDisplayName("Button width (px):"),
        DefaultValue(125),
        Personalizable(PersonalizationScope.Shared)]
        public int ButtonWidth
        {
            get
            {
                return _width;
            }

            set
            {
                _width = value;
            }
        }

        public static bool ViewExists(SPList list, string viewName)
        {
            return list.Views.Cast<SPView>().Any(view => string.Equals(view.Title, viewName));
        }

        private bool _editMode;

        protected override void OnPreRender(EventArgs e)
        {
            if (SPWebPartManager.GetCurrentWebPartManager(Page).DisplayMode != WebPartManager.BrowseDisplayMode)
            {
                _editMode = true;
            }
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            SPList list = SPContext.Current.Web.Lists.TryGetList(this.LinksListName);
            string webUrl = SPContext.Current.Web.ServerRelativeUrl;

            if (webUrl == "/")
            {
                webUrl = "";
            }

            if (list != null)
            {
                writer.Write(string.Format("<link type=\"text/css\" href=\"{0}/LinkButtonResources/css/smoothness/jquery-ui-1.8.4.custom.css\" rel=\"stylesheet\" />", webUrl));
                writer.Write(string.Format("<script type=\"text/javascript\" src=\"{0}/LinkButtonResources/js/jquery-1.4.2.min.js\"></script>", webUrl));
                writer.Write(string.Format("<script type=\"text/javascript\" src=\"{0}/LinkButtonResources/js/jquery-ui-1.8.4.custom.min.js\"></script>", webUrl));

                writer.Write("<script type=\"text/javascript\">");
                writer.Write("function openPage(Page, Title, Width, Height) {");
                writer.Write("var options = SP.UI.$create_DialogOptions();");
                writer.Write("options.width = Width;");
                writer.Write("options.height = Height;");
                writer.Write("options.url = Page;");
                writer.Write("options.title = Title;");

                writer.Write("SP.UI.ModalDialog.showModalDialog(options);");
                writer.Write("}");

                writer.Write("</script>");

                string width = "";

                switch (this.DisplayType)
                {
                    case DisplayTypeEnum.Resizable:
                        width = "";
                        break;
                    case DisplayTypeEnum.FixedSize:
                        width = string.Format(" style='width:{0}px'", this.ButtonWidth);
                        break;
                    case DisplayTypeEnum.WebPartSize:
                        width = " style='width:100%'";
                        break;
                    default:
                        width = "";
                        break;
                }

                string paddingRight = "";
                if (this.ButtonLayout == ButtonLayoutEnum.Horizonatal)
                {
                    paddingRight = "padding-right:5px;float:left;";
                }

                string onClick, iconUrl="";
                SPFieldUrlValue url, icon;
                SPView view;

                if (this.ListView != null && this.ListView != "[Default]" && ViewExists(list, this.ListView))
                {
                    view = list.Views[this.ListView];
                }
                else
                {
                    view = list.DefaultView;
                }

                SPListItem linkItem;
                bool iconFieldExists = false;
                if(list.Fields.TryGetFieldByStaticName(AppConstants.ICON_FIELD_NAME)!=null)
                {
                    iconFieldExists = true;
                }

                writer.Write("<div class=\"LinkButtons\" style='padding-top:5px'>");
                foreach (SPListItem link in list.GetItems(view))
                {
                    linkItem = list.Items[link.UniqueId];

                    url = linkItem.GetFieldValueUrl("URL");
                    
                    //if (linkItem.ContentTypeId.ToString().StartsWith(AppConstants.POPUPLINK_CONTENTTYPEID))
                    //{
                    //    onClick = string.Format("javascript:openPage('{0}', '{1}', {2}, {3}); return false;", url.Url, linkItem["Caption"].ToString(), linkItem[new Guid("{EAFA18EE-00C0-4350-9939-9D96225AE421}")].ToString(), linkItem[new Guid("{16775ABA-6471-4DCC-B1A4-2EE4A32073EE}")].ToString());
                    //}
                    //else
                    //{
                        onClick = string.Format("location.href='{0}'", url.Url);
                    //}


                    if (iconFieldExists)
                    {
                        icon = linkItem.GetFieldValueUrl(AppConstants.ICON_FIELD_NAME);
                        if (icon.Url != null && icon.Url != "" && icon.Url.ToLower() != "http://" && icon.Url.ToLower() != "https://")
                        {
                            iconUrl = string.Format("<img src='{0}' style='padding-right:5px;' align='middle' border='0'/>", icon.Url);
                        }
                        else
                        {
                            iconUrl = "";
                        }
                    }

                    writer.Write("<div style='padding-bottom:5px;{3}text-align:left;'><a href='#' onClick=\"{1}\"{2}>{4}{0}</a></div>", url.Description, onClick, width, paddingRight, iconUrl);
                }
                writer.Write("</div>");

                writer.Write("<script type=\"text/javascript\">");
                writer.Write("$(function() {");
                writer.Write("$(\"button, input:submit, a\", \".LinkButtons\").button();");
                writer.Write("$(\"a\", \".LinkButtons\").click(function() { return false; });");
                writer.Write("});");
                writer.Write("</script>");
            }
            else if(_editMode)
            {
                writer.Write(string.Format("To configure Link Buttons Web Part, <a href='#' onclick=\"javascript:MSOTlPn_ShowToolPane2('Edit','{0}');\"'>open the tool pane</a>.", this.ClientID.Substring(this.ClientID.LastIndexOf("m_")+2)));
            }
        }
    }
}
